package com.zfcoding.redismybatisplus.services.servicesImpl;

import com.zfcoding.redismybatisplus.entities.userentity.User;
import com.zfcoding.redismybatisplus.rediscache.UserCache;
import com.zfcoding.redismybatisplus.respositories.UserRepository;
import com.zfcoding.redismybatisplus.services.UserService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserCache userCache;

    /*
    增加用户
    */
    @Override
    public int insert(User user) {

        var insertResult =  userRepository.insert(user);
        return insertResult;
    }

    /*
    用户.更新
    */
    @Override
    public int updateById(User user) {
        var result =  userRepository.updateById(user);
        if (result  > 0 ){
            userCache.delUser(user.getId());
        }
        return result;
    }

    /*
    用户.删除.id
    */
    @Override
    public int deleteById(int id) {

        var result =  userRepository.deleteById(id);
        if (result > 0 )
        {
            userCache.delUser(id);
        }
        return result;
    }

    /*
    用户.查询.列表
    */
    @Override
    public List<User> selectList() {
        return userRepository.selectList(null);
    }

    /*
    用户.查询.单体
    */
    @Override
    public User selectModel(int id) {
        if (userCache.exists(id))
            return userCache.getUser(id);
        //TODO ...线程安全...
        var result =  userRepository.selectById(id);
        userCache.saveUser(result);
        return result;
    }

    /*
增加用户
*/
    @Override
    public boolean insertObject(Object object) {

        var insertResult =  userCache.saveObject(object);
        return insertResult;
    }
}
